package xtreamclient


import kotlinx.coroutines.*
import java.io.BufferedInputStream
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.logging.Logger

interface VLCHandler {
    var process: Process?
    fun connect()
    fun playItem(streamURL:String, streamName:String="")
    val inLog: Logger
        get() = Logger.getLogger("VLCHandler")

    suspend fun printLogs() = coroutineScope{
        print(process)
        var bis = BufferedInputStream(process?.inputStream)
        var eis = BufferedInputStream(process?.errorStream)
        val buf = ByteArrayOutputStream()
        val eBuf = ByteArrayOutputStream()
        val handler = CoroutineExceptionHandler { _, exception ->
            println("Caught $exception")
        }
        launch(handler) {
            while (process?.isAlive == true) {

                var result = bis.read()
                buf.write(result)
                if (result == 10) {
                    inLog.finer(buf.toString("UTF-8"))
                    buf.reset()
                }
            }
        }

        launch(handler){
            File("vlcErrors.log").printWriter().use { writer ->
                while (process?.isAlive == true) {

                    //print("New")
                    var result = eis.read()
                    eBuf.write(result)

                    if (result == 10) {
                        val string = eBuf.toString("UTF-8")
                        //inLog.warning(string)
                        writer.write(string)
                        writer.flush()
                        eBuf.reset()
                    }
                }
            }
            println("File closed")
        }
    }
}